package com.magicstone.common;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.magicstone.common.Licence.service.Encryptor;

import net.coobird.thumbnailator.Thumbnails;

public class Helper {
	private final static Log logger = LogFactory.getLog(Helper.class);
	
	/*
	 * Generate a new name using md5 algorithm according to parameters.
	 * @param file File name.
	 * @param contentType File content type.
	 * @param size The size of file.
	 * @return New name.
	 */
	public static String generateFileName(String file, String contentType, Long size){
		Date now = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		return Encryptor.digest(file + contentType + size.toString() + calendar.getTimeInMillis());
	}

	/*
	 * Generate thumbnail for source image.
	 * @param source Source image file object.
	 * @param width The width of thumbnail.
	 * @param height The height of thumbnail.
	 * @return The data of thumbnail.
	 */
	public static byte[] generateThumbnail(File source, int width, int height){
		long start = System.currentTimeMillis();
		byte buffer[] = null;
		if(source.exists()){
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			try {
				//Thumbnails.of(source).size(width, height).outputFormat("png").toOutputStream(os);
				Thumbnails.of(source).forceSize(width, height).toOutputStream(os);
				//ImageIO.write(thumbnail, "png", os);
				buffer = os.toByteArray();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		long elapsed = System.currentTimeMillis() - start;
		logger.debug("Thumbnail gerneration executed :" + elapsed);
		return buffer;
	}

	public static String getExt(String contentType){
		String ext = "";
		if(null != contentType){
			int index = contentType.indexOf(".");
			ext = (index < (contentType.length() - 1)) ? contentType.substring(index + 1) : "";
		}
		return ext;
	}
	
	/**
	 * Get properties object from properties file which specified by fileName.
	 * @param fileName
	 * @return
	 */
	public static Properties getProperties(String fileName){
		Properties pro = new Properties();
		InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
		try {
			pro.load(is);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return pro;
	}
}
